// 引入路由
import router from '@/router';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getRouter } from "@/api/system/user";


NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
})


// 路由拦截器
router.beforeEach((to, from, next) => {
  NProgress.start();
  if(asyncRoutes[0].children.length === 0){
    handlerRouter();
  }
    if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
      if (Boolean(localStorage.getItem("userInfo"))) {
        // 通过vuex state获取当前的user是否存在
        next();
      } else {
        next({
          path: '/login',
          query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
        })
      }
    } else {
      next();
    }
})

router.afterEach(() => {
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
})

// asyncRoutes 动态路由
const asyncRoutes = [
  {
    path: '/index',
    name: '首页',
    component: () => import('@/views/index'),
    hidden: false,
    meta: {
      requireAuth: true
    },
    children: []
  }
]

function handlerRouter() {
  getRouter({}).then(response => {
    let routerList = addDynamicRoutes(response.data)
    asyncRoutes[0].children = routerList
    router.addRoutes(asyncRoutes)
  })
}


// 路由动态生成(后端返回什么，就展示什么)
function addDynamicRoutes(res) {
  let menuList = [];
  res.forEach(v => {
    if (v.component != 'Layout'&&v.component!=null) {
      menuList.push({
        path: v.path,
        name: v.menuName,
        component: loadView(v.component),
        meta: {
          requireAuth: true
        },
        hidden: v.visible == '0' ? false : true
      })
    }
  });
  return menuList;
}



function loadView(view) {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}